package action

import (
	"strings"

	"gitee.com/sansaniot/ssiot-core/facade/env"
	"gitee.com/sansaniot/ssiot-core/logger"
	"gorm.io/gorm"

	"ssforward/common/constant"
	"ssforward/common/dto"
	"ssforward/common/utils"
	"ssforward/internal/forward/models"
	"ssforward/internal/forward/models/query"
)

type Broad struct {
	Orm *gorm.DB
}

func (action *Broad) Execute(topic string, jsonData map[string]interface{}) {
	if topic == constant.DeviceDeleteMsgTopic {
		handleDeviceDelete(action.Orm, jsonData)
	} else if topic == constant.DeviceAddMsgTopic {
		handleDeviceAdd(action.Orm, jsonData)
	}
}

func handleDeviceDelete(db *gorm.DB, jsonData map[string]interface{}) {
	sn, ok := jsonData["sn"]
	if !ok || sn == nil {
		return
	}
	snList := strings.Split(strings.ReplaceAll(sn.(string), " ", ""), ",")
	for _, v := range snList {
		if err := env.Cache.Del(constant.ForwardConfigKey + v); err == nil {
			constant.HasForwardConfigSn.Delete(v)
		}
	}
	logger.Info("(设备Delete)删除转发配置缓存")
}

func handleDeviceAdd(db *gorm.DB, jsonData map[string]interface{}) {
	sn, ok := jsonData["sn"]
	if !ok || sn == nil {
		return
	}
	devModel := &models.SysDev{}
	devModel.Orm = db
	if err := devModel.FindOne(devModel, dto.MakeCondition(query.SysDevQuery{Sn: sn.(string)})); err != nil {
		logger.Error(err)
		return
	}
	//查询转发配置
	if len(devModel.ProductModel) > 0 {
		db = db.Where("dev_sn = ? ", devModel.Sn).Or("product_model = ? ", devModel.ProductModel)
	} else {
		db = db.Where("dev_sn = ? ", devModel.Sn)
	}
	forwardRuleList := make([]models.SysForwardRule, 0)
	if err := db.Preload("ForwardServer").Find(&forwardRuleList).Error; err != nil {
		logger.Error(err)
		return
	}
	// 没有该设备/产品的转发规则
	if len(forwardRuleList) == 0 {
		return
	}
	// 规则集合
	productModelConfigMap := make(map[string][]models.SysForwardRule)
	devSnConfigMap := make(map[string][]models.SysForwardRule)
	for i, v := range forwardRuleList {
		if len(v.ProductModel) > 0 {
			if _, ok := productModelConfigMap[v.ProductModel]; !ok {
				productModelConfigMap[v.ProductModel] = make([]models.SysForwardRule, 0)
			}
			productModelConfigMap[v.ProductModel] = append(productModelConfigMap[v.ProductModel], forwardRuleList[i])
		}
		if len(v.DevSn) > 0 {
			if _, ok := devSnConfigMap[v.DevSn]; !ok {
				devSnConfigMap[v.DevSn] = make([]models.SysForwardRule, 0)
			}
			devSnConfigMap[v.DevSn] = append(devSnConfigMap[v.DevSn], forwardRuleList[i])
		}
	}
	snRuleMap := make(map[string][]models.SysForwardRule)
	if _, ok := snRuleMap[devModel.Sn]; !ok {
		snRuleMap[devModel.Sn] = make([]models.SysForwardRule, 0)
	}
	if rules, ok := productModelConfigMap[devModel.ProductModel]; ok {
		snRuleMap[devModel.Sn] = append(snRuleMap[devModel.Sn], rules...)
	}
	if rules, ok := devSnConfigMap[devModel.Sn]; ok {
		snRuleMap[devModel.Sn] = append(snRuleMap[devModel.Sn], rules...)
	}
	_ = env.Cache.Set(constant.ForwardConfigKey+devModel.Sn, utils.InterfaceToStr(snRuleMap[devModel.Sn]), -1)
	constant.HasForwardConfigSn.Store(devModel.Sn, devModel.Sn)
	logger.Info("(设备Add/服务操作)转发配置缓存")
}
